package com.abe.libquick.widget.aBook;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.abe.libcore.utils.CommonUtils;
import com.abe.libcore.utils.ToastUtils;
import com.abe.libcore.view.common.BaseCustomView;
import com.abe.libquick.R;
import com.abe.libquick.api.JsonHelper;
import com.abe.libquick.utils.NormalUtils;
import com.abe.libquick.utils.quick.EmptyUtils;
import com.abe.libquick.widget.aBook.listener.MultiSelectListener;
import com.abe.libquick.widget.aBook.listener.OnDismissListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.xw.repo.XEditText;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class AbeSuperABook<T extends ABookEntity> extends BaseCustomView
        implements OnItemClickListener, OnItemChildClickListener {

    private RelativeLayout ABookView, bgView;
    private XEditText itemEditSearch;
    private LinearLayout orgMemberV, searchMemberV;
    private RelativeLayout itemSearchHintV;
    private ImageView line01, line02;
    private View itemSelectV;
    private TextView itemSelectMember, itemSelectBtn;
    private List<T> allBookEntities, hOrgEntities, vOrgEntities, vMemberEntities, vSearchMemberEntities;
    private BaseQuickAdapter<T, BaseViewHolder> hOrgAdapter, vOrgAdapter, vMemberAdapter, vMemberSearchAdapter;

    private int selectLimit = 1;//限制选择人员数量
    private MultiSelectListener<T> selectListener;
    private OnDismissListener dismissListener;

    public AbeSuperABook(Context context) {
        super(context);
        focus();
    }

    @Override
    protected int getRootViewId() {
        return R.id.item_abe_a_book_view;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.item_view_abe_address_book_with_search;
    }

    @Override
    protected void initContent() {
        ABookView = findViewById(getRootViewId());
        bgView = findViewById(R.id.item_bg_v);
        orgMemberV = findViewById(R.id.item_org_member_v);
        searchMemberV = findViewById(R.id.item_search_member_v);
        itemSearchHintV = findViewById(R.id.item_search_hint_v);
        TextView itemEditSearchHint = findViewById(R.id.item_edit_search_hint);
        itemEditSearch = findViewById(R.id.item_edit_search);
        ImageView close = findViewById(R.id.item_close);
        line01 = findViewById(R.id.item_line_01);
        line02 = findViewById(R.id.item_line_02);
        RecyclerView itemHRv = findViewById(R.id.item_h_rv);
        RecyclerView itemVRvOrg = findViewById(R.id.item_v_rv_org);
        RecyclerView itemVRvMember = findViewById(R.id.item_v_rv_member);
        RecyclerView itemVRvSearchMember = findViewById(R.id.item_v_rv_search_member);
        itemSelectV = findViewById(R.id.item_select_v);
        itemSelectMember = findViewById(R.id.item_select_member);
        itemSelectBtn = findViewById(R.id.item_select_btn);
        /////////////////////////////////////////////////////
        itemSelectV.setVisibility(GONE);
        itemHRv.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        itemVRvOrg.setLayoutManager(new LinearLayoutManager(getContext()));
        itemVRvMember.setLayoutManager(new LinearLayoutManager(getContext()));
        itemVRvSearchMember.setLayoutManager(new LinearLayoutManager(getContext()));
        allBookEntities = new ArrayList<>();
        hOrgEntities = new ArrayList<>();
        vOrgEntities = new ArrayList<>();
        vMemberEntities = new ArrayList<>();
        vSearchMemberEntities = new ArrayList<>();
        hOrgAdapter = new BaseQuickAdapter<T, BaseViewHolder>(R.layout.item_view_abe_address_book_h_org, hOrgEntities) {

            @Override
            protected void convert(@NonNull BaseViewHolder helper, T item) {
                helper.setText(R.id.item_name, item.name());
                boolean isLast = helper.getLayoutPosition() == hOrgEntities.size() - 1;
                helper.setTextColor(R.id.item_name, getResources().getColor(isLast ? R.color.txt_9 : R.color.colorTheme));
                helper.getView(R.id.item_arrow).setVisibility(isLast ? GONE : VISIBLE);
            }
        };
        vOrgAdapter = new BaseQuickAdapter<T, BaseViewHolder>(R.layout.item_view_abe_address_book_v_org, vOrgEntities) {
            @Override
            protected void convert(@NonNull BaseViewHolder helper, T item) {
                helper.setText(R.id.item_name, item.name());
                helper.getView(R.id.item_img_choose).setVisibility(VISIBLE);
                helper.setImageResource(R.id.item_img_choose, item.select ? R.drawable.icon_abe_choose_1 : R.drawable.icon_abe_choose_0);
                helper.getView(R.id.item_open_child).setVisibility(VISIBLE);
                helper.getView(R.id.item_arrow).setVisibility(GONE);
            }
        };
        vOrgAdapter.addChildClickViewIds(R.id.item_open_child);
        vMemberAdapter = new BaseQuickAdapter<T, BaseViewHolder>(R.layout.item_view_abe_address_book_v_member, vMemberEntities) {
            @Override
            protected void convert(@NonNull BaseViewHolder helper, T item) {
                helper.setText(R.id.item_name, item.name());
                helper.getView(R.id.item_img_choose).setVisibility(VISIBLE);
                helper.setImageResource(R.id.item_img_choose, item.select ? R.drawable.icon_abe_choose_1 : R.drawable.icon_abe_choose_0);
            }
        };
        vMemberSearchAdapter = new BaseQuickAdapter<T, BaseViewHolder>(R.layout.item_view_abe_address_book_v_member_with_org, vSearchMemberEntities) {
            @Override
            protected void convert(@NotNull BaseViewHolder helper, T item) {
                helper.setText(R.id.item_name, item.name());
                helper.setText(R.id.item_org_name, item.orgName());
                helper.getView(R.id.item_img_choose).setVisibility(VISIBLE);
                helper.setImageResource(R.id.item_img_choose, item.select ? R.drawable.icon_abe_choose_1 : R.drawable.icon_abe_choose_0);
            }
        };
        hOrgAdapter.setOnItemClickListener(this);
        vOrgAdapter.setOnItemClickListener(this);
        vOrgAdapter.setOnItemChildClickListener(this);
        vMemberAdapter.setOnItemClickListener(this);
        vMemberSearchAdapter.setOnItemClickListener(this);
        itemHRv.setAdapter(hOrgAdapter);
        itemVRvOrg.setAdapter(vOrgAdapter);
        itemVRvMember.setAdapter(vMemberAdapter);
        itemVRvSearchMember.setAdapter(vMemberSearchAdapter);
        itemEditSearchHint.setOnClickListener(v -> {
            orgMemberV.setVisibility(GONE);
            searchMemberV.setVisibility(VISIBLE);
        });
        close.setOnClickListener(v -> {
            orgMemberV.setVisibility(VISIBLE);
            searchMemberV.setVisibility(GONE);
            itemEditSearch.setText("");
        });
        itemSelectBtn.setOnClickListener(v -> {
            super.dismiss();
            if (selectListener == null) return;
            selectListener.OnSelect(formatMultiSelect());
        });
        itemEditSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                formatSearchRvData();
            }
        });
        ABookView.setOnClickListener(v -> dismiss());
        bgView.setOnClickListener(v -> {
            //屏蔽点击
        });
        formatLine();
    }

    public AbeSuperABook<T> init(T rootEntity, List<T> aBookEntities) {
        itemSelectV.setVisibility(GONE);
        this.allBookEntities.clear();
        this.allBookEntities.addAll(aBookEntities);
        this.hOrgEntities.clear();
        this.hOrgEntities.add(rootEntity);
        hOrgAdapter.notifyDataSetChanged();
        formatByChildPid(rootEntity.id());
        formatSearchRvData();
        formatSelectV();
        focus();
        return this;
    }

    public AbeSuperABook<T> multiMember(int limitNum) {
        selectLimit = limitNum;
        itemSelectV.setVisibility(VISIBLE);
        itemSelectBtn.setText(formatLimit(0));
        itemSelectMember.setText("");
        itemSearchHintV.setVisibility(VISIBLE);
        return this;
    }

    public AbeSuperABook<T> multiSelect(MultiSelectListener<T> listener) {
        this.selectListener = listener;
        return this;
    }

    public AbeSuperABook<T> dismissCall(OnDismissListener listener) {
        this.dismissListener = listener;
        return this;
    }

    public void showAsDialog() {
        int paddingW = NormalUtils.dip2px(getContext(), 25);
        int paddingH = NormalUtils.dip2px(getContext(), 40);
        ABookView.setPadding(paddingW, paddingH, paddingW, paddingH);
        bgView.setBackgroundResource(R.drawable.item_white_bg);
        super.show();
        formatSelectV();
    }

    @Override
    public void show() {
        ABookView.setPadding(0, 0, 0, 0);
        bgView.setBackgroundResource(R.color.white);
        super.show();
        formatSelectV();
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if (dismissListener != null) {
            dismissListener.OnDismiss();
        }
    }

    private void formatByChildPid(String orgId) {
        List<T> childEntities = getEntityByOrgId(orgId);
        List<T> childOrg = new ArrayList<>();
        List<T> childMember = new ArrayList<>();
        for (int i = 0; i < childEntities.size(); i++) {
            T tem = childEntities.get(i);
            if (tem.isOrg()) {
                childOrg.add(tem);
            } else {
                childMember.add(tem);
            }
        }
        this.vOrgEntities.clear();
        this.vOrgEntities.addAll(childOrg);
        vOrgAdapter.notifyDataSetChanged();
        this.vMemberEntities.clear();
        this.vMemberEntities.addAll(childMember);
        vMemberAdapter.notifyDataSetChanged();
        formatLine();
    }

    private void formatSelectV() {
        List<T> select = formatMultiSelectMember();
        String x = "";
        for (int i = 0; i < select.size(); i++) {
            T temp = select.get(i);
            if (i == 0) {
                x = temp.name();
            } else {
                x = String.format(Locale.CHINA, "%s、%s", x, temp.name());
            }
        }
        itemSelectMember.setText(x);
        itemSelectBtn.setText(formatLimit(select.size()));
    }

    private String formatLimit(int hasSelectNum) {
        return String.format(Locale.CHINA, getResources().getString(R.string.select_person_confirm01), hasSelectNum, selectLimit);
    }

    private void formatLine() {
        line01.setVisibility(vOrgEntities.size() == 0 ? GONE : VISIBLE);
        line02.setVisibility(vMemberEntities.size() == 0 ? GONE : VISIBLE);
    }

    private List<T> getTreeMEntityByOrgId(String orgId) {
        List<T> entities = new ArrayList<>();
        for (int i = 0; i < allBookEntities.size(); i++) {
            T entity = allBookEntities.get(i);
            if (entity.orgId().equals(orgId)) {
                if (!entity.isOrg()) {
                    entities.add(entity);
                } else {
                    entities.addAll(getTreeMEntityByOrgId(entity.id()));
                }
            }
        }
        return entities;
    }

    private List<T> getTreeEntityByOrgId(String orgId) {
        List<T> entities = new ArrayList<>();
        for (int i = 0; i < allBookEntities.size(); i++) {
            T entity = allBookEntities.get(i);
            if (entity.orgId().equals(orgId)) {
                entities.add(entity);
                if (entity.isOrg()) {
                    entities.addAll(getTreeEntityByOrgId(entity.id()));
                }
            }
        }
        return entities;
    }

    private int getEntityById(String id) {
        int x = -1;
        for (int i = 0; i < allBookEntities.size(); i++) {
            if (allBookEntities.get(i).id().equals(id)) {
                x = i;
            }
        }
        return x;
    }

    private List<T> getEntityByOrgId(String orgId) {
        List<T> entities = new ArrayList<>();
        for (int i = 0; i < allBookEntities.size(); i++) {
            T entity = allBookEntities.get(i);
            if (entity.orgId().equals(orgId)) {
                entities.add(entity);
            }
        }
        return entities;
    }

    private void formatOrgAllChild(List<T> allCache, String id, boolean select) {
        for (int i = 0; i < allCache.size(); i++) {
            T temp = allCache.get(i);
            if (temp.orgId().equals(id)) {
                temp.select = select;
                allCache.set(i, temp);
                if (temp.isOrg()) {
                    formatOrgAllChild(allCache, temp.id(), select);
                }
            }
        }
    }

    private List<T> formatMultiSelectMember() {
        List<T> select = new ArrayList<>();
        for (int i = 0; i < allBookEntities.size(); i++) {
            T temp = allBookEntities.get(i);
            if (temp.select && !temp.isOrg()) {
                select.add(allBookEntities.get(i));
            }
        }
        return select;
    }

    private List<T> formatMultiSelect() {
        List<T> select = new ArrayList<>();
        for (int i = 0; i < allBookEntities.size(); i++) {
            if (allBookEntities.get(i).select) {
                select.add(allBookEntities.get(i));
            }
        }
        return select;
    }

    private void formatSearchRvData() {
        if (EmptyUtils.isEmpty(allBookEntities)) return;
        String key = itemEditSearch.getText().toString();
        List<T> tempEntities = new ArrayList<>();
        for (int i = 0; i < allBookEntities.size(); i++) {
            T temp = allBookEntities.get(i);
            if (temp.name().contains(key) && !temp.isOrg()) {
                tempEntities.add(temp);
            }
        }
        vSearchMemberEntities.clear();
        vSearchMemberEntities.addAll(tempEntities);
        if (vMemberSearchAdapter != null) vMemberSearchAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        T entity = vOrgEntities.get(position);
        this.hOrgEntities.add(entity);
        hOrgAdapter.notifyDataSetChanged();
        formatByChildPid(entity.id());
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == hOrgAdapter) {
            if (position == hOrgEntities.size() - 1) return;
            T entity = hOrgEntities.get(position);
            List<T> tempEntities = new ArrayList<>(hOrgEntities.subList(0, position + 1));
            CommonUtils.INSTANCE.log(JsonHelper.gson(JsonHelper.JSON_C_SHAPE).toJson(tempEntities));
            this.hOrgEntities.clear();
            this.hOrgEntities.addAll(tempEntities);
            hOrgAdapter.notifyDataSetChanged();
            formatByChildPid(entity.id());
        } else if (adapter == vOrgAdapter) {
            T entity = vOrgEntities.get(position);
            if (entity.select) {
                List<T> allCache = new ArrayList<>(allBookEntities);
                entity.select = false;
                allCache.set(getEntityById(entity.id()), entity);
                formatOrgAllChild(allCache, entity.id(), false);
                cancelTreePEntityById(allCache, entity.id());
                allBookEntities.clear();
                allBookEntities.addAll(allCache);
                formatByChildPid(entity.orgId());
                formatSearchRvData();
                formatSelectV();
            } else {
                List<T> selectMember = formatMultiSelectMember();
                if (selectMember.size() >= selectLimit) {
                    ToastUtils.INSTANCE.show(getContext(), String.format(Locale.CHINA,
                            getResources().getString(R.string.select_person_limit), selectLimit));
                    return;
                }
                List<T> allTreeChildMember = getTreeMEntityByOrgId(entity.id());
                int tempNum = selectMember.size() + allTreeChildMember.size();
                if (tempNum > selectLimit) {
                    ToastUtils.INSTANCE.show(getContext(), String.format(Locale.CHINA,
                            getResources().getString(R.string.select_person_limit), selectLimit));
                    return;
                }
                List<T> allCache = new ArrayList<>(allBookEntities);
                entity.select = true;
                allCache.set(getEntityById(entity.id()), entity);
                formatOrgAllChild(allCache, entity.id(), true);
                fillTreePEntityById(allCache, entity.id());
                allBookEntities.clear();
                allBookEntities.addAll(allCache);
                formatByChildPid(entity.orgId());
                formatSearchRvData();
                formatSelectV();
            }
        } else if (adapter == vMemberAdapter) {
            T entity = vMemberEntities.get(position);
            if (entity.select) {
                List<T> allCache = new ArrayList<>(allBookEntities);
                entity.select = false;
                allCache.set(getEntityById(entity.id()), entity);
                cancelTreePEntityById(allCache, entity.id());
                allBookEntities.clear();
                allBookEntities.addAll(allCache);
                formatByChildPid(entity.orgId());
                formatSearchRvData();
                formatSelectV();
            } else {
                List<T> selectMember = formatMultiSelectMember();
                if (selectMember.size() >= selectLimit) {
                    ToastUtils.INSTANCE.show(getContext(), String.format(Locale.CHINA,
                            getResources().getString(R.string.select_person_limit), selectLimit));
                    return;
                }
                List<T> allCache = new ArrayList<>(allBookEntities);
                entity.select = true;
                allCache.set(getEntityById(entity.id()), entity);
                fillTreePEntityById(allCache, entity.id());
                allBookEntities.clear();
                allBookEntities.addAll(allCache);
                formatByChildPid(entity.orgId());
                formatSearchRvData();
                formatSelectV();
            }
        } else if (adapter == vMemberSearchAdapter) {
            T entity = vSearchMemberEntities.get(position);
            if (entity.select) {
                List<T> allCache = new ArrayList<>(allBookEntities);
                entity.select = false;
                allCache.set(getEntityById(entity.id()), entity);
                cancelTreePEntityById(allCache, entity.id());
                allBookEntities.clear();
                allBookEntities.addAll(allCache);
                formatByChildPid(hOrgEntities.get(hOrgEntities.size() - 1).id());
                formatSearchRvData();
                formatSelectV();
            } else {
                List<T> selectMember = formatMultiSelectMember();
                if (selectMember.size() >= selectLimit) {
                    ToastUtils.INSTANCE.show(getContext(), String.format(Locale.CHINA,
                            getResources().getString(R.string.select_person_limit), selectLimit));
                    return;
                }
                List<T> allCache = new ArrayList<>(allBookEntities);
                entity.select = true;
                allCache.set(getEntityById(entity.id()), entity);
                fillTreePEntityById(allCache, entity.id());
                allBookEntities.clear();
                allBookEntities.addAll(allCache);
                formatByChildPid(hOrgEntities.get(hOrgEntities.size() - 1).id());
                formatSearchRvData();
                formatSelectV();
            }
        }
    }

    private void fillTreePEntityById(List<T> allCache, String id) {
        T temp = allCache.get(getEntityById(id));
        boolean allCheck = true;
        for (int i = 0; i < allCache.size(); i++) {
            T entity = allCache.get(i);
            if (entity.orgId().equals(temp.orgId())) {
                if (!entity.select) {
                    allCheck = false;
                }
            }
        }
        if (allCheck) {
            int tempPPos = getEntityById(temp.orgId());
            if (tempPPos < 0) return;
            T tempP = allCache.get(tempPPos);
            tempP.select = true;
            allCache.set(tempPPos, tempP);
            fillTreePEntityById(allCache, temp.orgId());
        }
    }

    private void cancelTreePEntityById(List<T> allCache, String id) {
        T temp = allCache.get(getEntityById(id));
        int tempPPos = getEntityById(temp.orgId());
        if (tempPPos < 0) return;
        T tempP = allCache.get(tempPPos);
        if (tempP.select) {
            tempP.select = false;
            allCache.set(tempPPos, tempP);
            cancelTreePEntityById(allCache, tempP.id());
        }
    }
}